package com.bt.lms.ui.action.teaching.arrange;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.BOConstant;
import com.bt.lms.constants.TeachingArrangeBizTypeConstant;
import com.bt.lms.entity.TeachingArrangeInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.page.common.action.pageteaching.TeachingArrangeLabAction;
import com.bt.lms.ui.page.teaching.arrange.PageAddTeachingArrange;
import com.bt.lms.ui.page.teaching.arrange.PageArrangeNoExecuteList;
import com.bt.lms.ui.page.teaching.arrange.vo.AddTeachingArrangeVo;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.time.LocalDate;

/**
 * 新增教学安排保存并确认开课事件
 */
public class PageAddTeachingArrangeStartCourseBtnAction implements EventHandler {

    /**
     * 教学安排界面
     */

    private PageAddTeachingArrange pageAddTeachingArrange;

    @Override

    public void handle(Event event) {

        //1.获取用户输入
        AddTeachingArrangeVo addTeachingArrangeVo = getInPrams();


        //2.验证用户输入内容
        String validDateMsg = validateInParam(addTeachingArrangeVo);

        //3.组包
        byte[] bytes = null;
        if (null == validDateMsg) {
            bytes = handleReqMsg(addTeachingArrangeVo);

        } else {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(validDateMsg);
            alert.showAndWait();

            return;
        }

        //4.组网
        Socket socket = getNet();

        //5.发送消息
        boolean sendReqMsg = sendReqMsg(socket, bytes);


        //返回列表界面
        PageArrangeNoExecuteList pageArrangeNoExecuteList = new PageArrangeNoExecuteList();
        Pane pane = TeachingArrangeLabAction.pageSkipInfo.getPane();
        Integer index = TeachingArrangeLabAction.pageSkipInfo.getIndex();
        pane.getChildren().set(index, pageArrangeNoExecuteList);

//        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
//        alert.setContentText("保存并确认开课吗");
//        alert.show();


    }

    /**
     * 发消息
     *
     * @param socket
     * @param bytes
     * @return
     */
    private boolean sendReqMsg(Socket socket, byte[] bytes) {


        try {
            //输出流
            OutputStream out = socket.getOutputStream();
            out.write(bytes);//写出
            out.flush();


            //6.接收服务端消息
            InputStream in = socket.getInputStream();
            byte[]buffer = new byte[1024];
            in.read(buffer);
            in.close();
            out.close();
            socket.close();


        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return true;
    }




    /**
     * 组网
     *
     * @return
     */
    private Socket getNet() {

        //ip，端口号
        String ip = "127.0.0.1";
        Integer port = 8888;
        Socket socket = null;

        try {
            socket = new Socket(ip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return socket;


    }

    /**
     * 组包
     *
     * @param addTeachingArrangeVo 教学安排输入的信息
     * @return byte数组
     */
    private byte[] handleReqMsg(AddTeachingArrangeVo addTeachingArrangeVo) {
        //请求消息
        ReqMsg reqMsg = new ReqMsg();

        //教学安排信息
        TeachingArrangeInfo teachingArrangeInfo = new TeachingArrangeInfo();

        //设置业务类型
        reqMsg.setBizType(TeachingArrangeBizTypeConstant.TEACHING_ARRANGE_INFO_ADD_AFFIRM_COURSE);

        //请求id时间戳
        long l = System.currentTimeMillis();
        reqMsg.setReqId(l);


        try {
            //vo转entity
            BeanUtils.copyProperties(teachingArrangeInfo, addTeachingArrangeVo);

            teachingArrangeInfo.setStatus(BOConstant.TEACHING_ARRANGE_INFO_STATUS_PUBLISHED);
            String teachingArrangeStr = JSON.toJSONString(teachingArrangeInfo);




            reqMsg.setData(teachingArrangeStr);


        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        byte[] bytes = reqMsg.toBytes();


        return bytes;
    }

    /**
     * 验证用户输入
     *
     * @param addTeachingArrangeVo 教学安排vo对象
     * @return 验证结果
     */
    private String validateInParam(AddTeachingArrangeVo addTeachingArrangeVo) {
        String msg = "";

        //设置课程
        String course = addTeachingArrangeVo.getCourse();
        String courseNull = "请设置课程\r\n";

        if (course.equals("")) {
            msg += courseNull;

        }
        //设置教师
        String teacher = addTeachingArrangeVo.getTeacher();
        String teacherNull = "请设置教师，教师必填\r\n";
        if (teacher.equals("")) {
            msg += teacherNull;
        }

        //设置班级部分
        String setClass = addTeachingArrangeVo.getSetClass();
        String setClassNull = "请设置班级，班级必填\r\n";
        if (setClass.equals("")) {
            msg += setClassNull;

        }
        //开课时间部分
        LocalDate startCourseTime = addTeachingArrangeVo.getStartCourseTime();
        String startCourseTimeNull = "开课时间不能为空\r\n";
        String choiceTrueTime = "请选择正确的时间\r\n";


        if (startCourseTime == null) {
            msg += startCourseTimeNull;

        } else {

            LocalDate now = LocalDate.now();//获取现在的时间
            int monthValue = LocalDate.now().getMonthValue();//获取月
            int dayOfMonth = LocalDate.now().getDayOfMonth();//获取月中的哪天
            int nowYear = now.getYear();//获取当前的年
            int year = startCourseTime.getYear();

            if (year < nowYear) {
                msg += choiceTrueTime;
            }


        }
        //结课时间部分
        LocalDate endCourseTime = addTeachingArrangeVo.getFinishCourseTime();
        String endCourseTimeNull = "结课时间必填\r\n";
        String noAfter = "结课时间不能在开课时间之前\r\n";

        if (endCourseTime == null) {
            msg += endCourseTimeNull;

        } else {
            LocalDate now = LocalDate.now();
            int monthValue = LocalDate.now().getMonthValue();//获取月
            int dayOfMonth = LocalDate.now().getDayOfMonth();//获取月中的哪天

            int i = endCourseTime.compareTo(startCourseTime);//开课时间跟结课时间对比
            if (i <= 0) {
                msg += noAfter;

            }


        }

        //课程目标部分
        String courseAim = addTeachingArrangeVo.getCourseAim();
        String courseAimNull = "课程目标必填\r\n";
        String courseLen = "课程目标字数长度255字\r\n";
        if (courseAim.equals("")) {
            msg += courseAimNull;
        }
        if (courseLen.length() > 255) {
            msg += courseLen;

        }


        //返回结果
        if ("".equals(msg)) {
            return null;
        } else {
            return msg;
        }
    }

    /**
     * 获取用户输入
     *
     * @return vo对象
     */
    private AddTeachingArrangeVo getInPrams() {

        //组装成vo对象
        AddTeachingArrangeVo addTeachingArrangeVo = new AddTeachingArrangeVo();

        //设置课程部分
        TextField setCourseTF = (TextField) pageAddTeachingArrange.lookup("#setCourseTF");
        String setCourseStr = setCourseTF.getText();
        addTeachingArrangeVo.setCourse(setCourseStr);

        //设置教师部分
        TextField setTeacherTF = (TextField) pageAddTeachingArrange.lookup("#setTeacherTF");
        String setTeacherStr = setTeacherTF.getText();
        addTeachingArrangeVo.setTeacher(setTeacherStr);

        //设置学员部分
        TextField detailTF = (TextField) pageAddTeachingArrange.lookup("#detailTF");
        String detailTStr = detailTF.getText();
        addTeachingArrangeVo.setSetClass(detailTStr);


        //教学方式部分
        ComboBox teachingWayCB = (ComboBox) pageAddTeachingArrange.lookup("#teachingWayCB");
        String teachingWayValue = (String) teachingWayCB.getValue();
        Integer teachingWay = -1;

        switch (teachingWayValue) {
            case "在线学习":
                teachingWay = 1;
                break;

            case "面授学习":
                teachingWay = 2;
                break;

            case "混合式学习":
                teachingWay = 3;
                break;

        }
        addTeachingArrangeVo.setTeachingWay(teachingWay);


        //开课时间部分
        DatePicker startCourseDP = (DatePicker) pageAddTeachingArrange.lookup("#startCourseDP");
        LocalDate startCourseDPValue = startCourseDP.getValue();
        addTeachingArrangeVo.setStartCourseTime(startCourseDPValue);


        //结课时间部分
        DatePicker finishCourseDP = (DatePicker) pageAddTeachingArrange.lookup("#finishCourseDP");
        LocalDate finishCourseDPValue = finishCourseDP.getValue();
        addTeachingArrangeVo.setFinishCourseTime(finishCourseDPValue);


        //课程目标部分
        TextArea courseAimTA = (TextArea) pageAddTeachingArrange.lookup("#courseAimTA");
        String courseAimStr = courseAimTA.getText().trim();
        addTeachingArrangeVo.setCourseAim(courseAimStr);


        return addTeachingArrangeVo;

    }


    public PageAddTeachingArrange getPageAddTeachingArrange() {
        return pageAddTeachingArrange;
    }

    public void setPageAddTeachingArrange(PageAddTeachingArrange pageAddTeachingArrange) {
        this.pageAddTeachingArrange = pageAddTeachingArrange;
    }
}
